package com.gaoqi.springboot_shiro.config.shiro.realm;

import com.gaoqi.springboot_shiro.config.shiro.salt.MySimpleByteSource;
import com.gaoqi.springboot_shiro.pojo.Role;
import com.gaoqi.springboot_shiro.pojo.User;
import com.gaoqi.springboot_shiro.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Collections;
import java.util.List;

//自定义realm 需要继承 AuthorizingRealm
public class CustomerRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    //授权控制
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取身份信息
        String uname = principalCollection.toString();
        System.out.println("======================开始授权=========================");
        //根据身份信息 查询数据库 添加改用户的 角色
        System.out.println("============授权——数据库查询用户角色信息==============");
        List<Role> roles = userService.findRolesByUname(uname).getRoles();

//        System.out.println(roles);

        try {
            //判断roles 集合是否为null（角色处理）
            if (!CollectionUtils.isEmpty(roles)) {
                SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
                for (Role r : roles
                ) {
                    //添加由用户名查询的角色集合 用于角色判断
                    simpleAuthorizationInfo.addRole(r.getRtype());
                    //通过用户角色id 获取权限
                    Role role = userService.findPremissionById(r.getRid());
//                System.out.println(role);
                    //判断获取的集合不为空（权限处理 ）
                    if (!CollectionUtils.isEmpty(role.getPremissions())) {

                        //添加权限 lambda 表达式
                        role.getPremissions().forEach((pres) -> {
                            simpleAuthorizationInfo.addStringPermission(pres.getUrl());
                        });
                    }
                }
                return simpleAuthorizationInfo;
            }

        } catch (AuthorizationException e) {
            e.printStackTrace();
            System.out.println("权限验证失败");
        }
        return null;
    }


    //认证控制
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("======================开始认证=========================");
        //获取用户身份信息
        String principal = (String) authenticationToken.getPrincipal();

        //通过身份信息 查询该用户是否存在
        System.out.println("===========认证——用户名查询数据库获取用户信息============");
        User user = userService.findUserByUname(principal);

        //用户身份信息验证
        if (user != null) {
            //传入用户身份信息 用户密码 随机盐 等
            System.out.println("=====================AddSalt======================");
            SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                    user.getUname(),
                    user.getPswd(),
                    new MySimpleByteSource(user.getSalt()),
                    this.getName()
            );

            return authenticationInfo;
        }
        return null;
    }
}
